package util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DatabaseInitializer {
    public static void initializeDatabase() {
        // Get the absolute path to the SQL file
        String projectDir = System.getProperty("user.dir");
        Path sqlPath = Paths.get(projectDir, "src", "sql", "create_students_table.sql");
        
        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             BufferedReader reader = new BufferedReader(new FileReader(sqlPath.toFile()))) {
            
            StringBuilder sql = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sql.append(line);
                if (line.contains(";")) {
                    stmt.execute(sql.toString());
                    sql.setLength(0);
                }
            }
            System.out.println("Database tables initialized successfully.");
        } catch (SQLException | IOException e) {
            System.err.println("Error initializing database: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
